package leetcode.doublepointer;

import java.util.Arrays;

//557. 反转字符串中的单词 III
public class ReverseWords {

    public static void main(String[] args) {
      String s=   "Let's take LeetCode contest";
        System.out.println(reverseWords(s).length());
        System.out.println(reverseWords2(s));
    }
    public static String reverseWords(String s) {
        String res = "";
        String[] data = s.split(" ");
        for (int i = 0; i < data.length; i++) {
            char[] chars = data[i].toCharArray();
            reverseString(chars);
            if (i==data.length-1){
                res  +=  String.valueOf(chars);
            }else {
                res  +=  String.valueOf(chars)+" ";
            }

        }
        return res;
    }
    public static void reverseString(char[] s) {
        int p =0;
        int q = s.length-1;
        while (p<q){
            char tmp = s[p];
            s[p] = s[q];
            s[q] = tmp;
            p++;
            q--;
        }
    }



    public static String reverseWords2(String s) {
        char[] chars = s.toCharArray();
        int p =0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i]==' '){
                reverseString2(chars,p,i-1);
                p = i+1;
            }
            //由于最后没有空格
            if (i==chars.length-1){
                reverseString2(chars,p,i);
            }
        }
        return new String(chars);
    }

    public static void reverseString2(char[] s,int start ,int end) {
        int p =start;
        int q = end;
        while (p<q){
            char tmp = s[p];
            s[p] = s[q];
            s[q] = tmp;
            p++;
            q--;
        }
    }
}
